package cm.util.chart.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;

import cm.util.chart.PieChart;
import cm.util.exception.MessageException;
import cm.util.hibernate.HibernateSessionFactory;

import com.opensymphony.xwork2.ActionSupport;

public class PieChartSQLAction extends ActionSupport {

	private static final long serialVersionUID = -6381994023987145818L;

	private String title;

	private int width;

	private int height;

	private String sql;

	public PieChartSQLAction(String title, int width, int height, String sql) {
		this.title = title;
		this.width = width;
		this.height = height;
		this.sql = sql;
	}

	@Override
	public String execute() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();

		JFreeChart chart = PieChart.createChart(title, getDataset());

		try {
			ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart,
					width, height);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private PieDataset getDataset() {
		Session session = HibernateSessionFactory.getSession();
		DefaultPieDataset dataset = new DefaultPieDataset();
		try {
			SQLQuery query = session.createSQLQuery(sql);
			List<Object[]> list = query.list();
			for (Object[] obs : list) {
				if (obs.length != 2) {
					StringBuffer buffer = new StringBuffer();
					for (Object ob : obs) {
						buffer.append(ob + "  ");
					}

					throw new MessageException("数据不合法!  " + buffer);
				}

				dataset.setValue(obs[0].toString(), Integer.parseInt(obs[1]
						.toString()));
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return dataset;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public String getSql() {
		return sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

}
